import type { PropType } from 'vue'
import { defineComponent } from 'vue'
import { ElButton, ElDialog } from 'element-plus'
import { FormGrid, FormItem, FormLayout, Select } from '@formily/element-plus'
import type { Field } from '@formily/core'
import { createForm, isField, onFieldInit } from '@formily/core'
import SchemaForm from '@/components/SchemaForm'
import exportSchema from '@/views/student/list/schema/exportSchema'
import type { Tree } from '@/api/system/user'
import useAddress from '@/hooks/useAddress'
import { download } from '@/utils/request'

export default defineComponent({
  props: {
    deptOptions: {
      type: Object as PropType<Tree[]>,
    },
    modelValue: {
      type: Boolean,
    },
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const transformDept = (data: Tree[]) => data.map(item => ({ label: item.label, value: item.label, children: item.children }))
    const exportForm = createForm<{ [k in keyof typeof exportSchema]: string }>({
      effects: () => {
        onFieldInit('layout.gird.province', async (field) => {
          if (isField(field)) {
            field.loading = true
            const data = await useAddress(
              (data: Record<string, any>) => Object.values(data).map(value => ({ label: value.name, value: value.name })),
            )
            field.loading = false
            field.dataSource = data
          }
        })
        onFieldInit('layout.gird.studentCollege', async (field) => {
          if (isField(field) && props.deptOptions)
            field.dataSource = transformDept(props.deptOptions)
        })
      },
    })
    function querySchoolDictByPre(field: Field, dataSource?: { label: string; value: string; children: Tree[] }[], value?: string) {
      const pre = dataSource?.find(item => item.value === value)
      if (pre) {
        field.loading = true
        field.dataSource = transformDept(pre.children || [])
        if (field.dataSource.findIndex(item => item.value === field.value) === -1)
          field.value = null
        field.loading = false
      }
    }
    function submitExport() {
      void exportForm.submit((values) => {
        void download(
          '/system/infor/export',
          values,
          `user_${new Date().getTime()}.xlsx`,
          {
            headers: {
              'Content-Type': 'application/json',
            },
          },
        )
      })
    }
    return () => (
      <ElDialog
        modelValue={props.modelValue}
        onUpdate:modelValue={value => emit('update:modelValue', value)}
        title="导出数据"
        width="750px"
        append-to-body
      >
        {{
          default: () => (
            <SchemaForm
              form={exportForm}
              schema={exportSchema}
              components={{ FormGrid, Select, FormItem, FormLayout }}
              scope={{ querySchoolDictByPre }}
            />
          ),
          footer: () => (
            <div class="dialog-footer">
              <ElButton type="primary" onClick={submitExport}>
                确 定
              </ElButton>
              <ElButton onClick={() => emit('update:modelValue', false)}>
                取 消
              </ElButton>
            </div>
          ),
        }}
      </ElDialog>
    )
  },
})
